<?php
/**
 * 根据指示符搜索节点
 * @param simple_html_dom_node|array &$dom 要操作的节点或者节点组
 * @param string $tag 标签名
 * @param string $opt 指示符,目前支持>~+
 * @param array &$retarr 要追回到的数组
 * @return array
 */
function select_elements(&$dom,$tag,$opt,&$retarr=null){
    $ret = array();
    if(!empty($tag) && !empty($opt)){
        $domp = null;
        if(!is_array($dom)) $domp = array(&$dom);
        else  $domp = &$dom;
        foreach($domp as &$dpx){//$dpx 为simple_html_dom_node类型
            if($dpx instanceof simple_html_dom_node == false) continue;
            if($opt == '>'){//子级节点
                if(!empty($dpx->children)){
                    foreach($dpx->children as &$childx){
                        if($childx->tag == $tag) $ret[] = &$childx;
                    }
                    unset($childx);
                }
            }
            elseif($opt == '~'){//兄弟节点
                $curparent = $dpx->parent();
                foreach($dpx->children as &$childx){
                    if($dpx !== $childx && $childx->tag == $tag){
                        $ret[] = &$childx;
                    }
                }
                unset($childx);
            }
            elseif($opt == '+'){//相邻节点
                $ppr = $dpx->previousSibling();
                if($ppr != null && $ppr->tag == $tag) $ret[] = &$ppr;
                $ppr = $dpx->nextSibling();
                if($ppr != null && $ppr->tag == $tag) $ret[] = &$ppr;
                unset($ppr);
            }
            unset($dpx);
        }
    }
    if($retarr !== null && is_array($retarr) && !empty($ret)){
        foreach($ret as &$r) $retarr[] = &$r;
    }
    return $ret;
}


function do_http_post($url, $post = '', $cookie='',$header='', $timeout = 30, $times = 3) {
    if(substr($url, 0, 8) == 'https://') {
        return https_post($url, $post, $cookie, $timeout, $times);
    }
    is_array($post) AND $post = http_build_query($post);
    is_array($cookie) AND $cookie = http_build_query($cookie);
    $header .= "Content-type: application/x-www-form-urlencoded\r\nx-requested-with: XMLHttpRequest\r\nCookie: $cookie\r\n";
    $stream = stream_context_create(array('http' => array('header' => $header, 'method' => 'POST', 'content' => $post, 'timeout' => $timeout)));
    $s = null;
    while($times-- > 0) {
        $s = file_get_contents($url, false, $stream, 0, 4096000);
        if($s !== FALSE) {
           break;
        }
    }
    unset($stream);
    if(empty($s)) return FALSE;
    return $s;
}
class CSVOpt{

    function ReadCsv(string $csvPath){
        if(is_file($csvPath)){
            $file = fopen($csvPath,'r');
            if(is_resource($file)){
                $datas = array();
                while ($data = fgetcsv($file)) {    //每次读取CSV里面的一行内容
                    $datas[] = &$data;
                    unset($data);
                }
                fclose($file);
                return $datas;
            }
        }
        return false;
    }

    function WriteCsv(string $csvPath,array &$data,$Append=false,$encoding='GB2312'):int{
        $ret = 0;
        $mode = 'w';
        if($Append) $mode = 'a+';
        $fp = fopen($csvPath, $mode);
        if(is_resource($fp)) {
            foreach($data as $dk => &$dv){
                if($encoding != 'UTF-8'){
                    $dv2 = array();
                    foreach($dv as $dvi){
                        //处理,"
                        if(strpos($dvi,',') !== false){
                            $dvi = '"'.str_replace('"','\'',$dvi).'"';
                        }
                        $dv2[] = iconv("UTF-8", "GBK//IGNORE", $dvi);  //这里将utf-8转为GB2312编码进行保存
                    }
                    unset($dv);
                    $dv = &$dv2;
                }
                $ret += (fputcsv($fp, $dv) > 0 ? 1 : 0);
            }
            fclose($fp);
        }
        return $ret;
    }

    protected function download_send_headers(string $filename) {
        // disable caching
        $now = gmdate("D, d M Y H:i:s");
        header("Expires: Mon, 05 Oct 2020 00:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
        // force download
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        // disposition / encoding on response body
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");
    }

    function array2csv(array &$array,array &$head=null)
    {
        if (count($array) == 0) {
            return null;
        }
        ob_start();
        $df = fopen("php://output", 'w');
        if(!$head){
            $head=array_keys(reset($array));
        }
        fputcsv($df,$head);
        foreach ($array as &$row) {
            fputcsv($df, $row);
        }
        fclose($df);
        return ob_get_clean();
    }

    function DownloadCsv(string $csvPath,array &$data = null,array &$head=null){
        if(is_file($csvPath) || !empty($data)){
            if(!is_file($csvPath)){
                $this->WriteCsv($csvPath,$data);
            }
            ob_end_clean();
            $this->download_send_headers(pathinfo($csvPath,PATHINFO_BASENAME));
            readfile($csvPath);//不要带echo;
            return true;
        }
        return false;
    }

}

function GetDomSelectValue(string &$html){
    $gwlb = '';
    if($html != null){
        $ftxts = preg_replace('/^[\s　]+|[\s　]+$/us','',$html);
        //先找√
        $fchrs = array('√','✔','☑','☒','■','★','▲','◎','☆','●','◆','△','R','S');
        $fclen = 1;
        foreach($fchrs as $fc){
            $px1 = strpos($ftxts,$fc);
            if($px1 !== false){
                $fclen = strlen($fc);
                break;
            }
        }
        if($px1 === false) $px1 = strpos($ftxts,'□ ');
        if($px1 !== false){
            $px2 = strpos($ftxts,'□',$px1+$fclen);
            if($px2 === false) $px2 = strpos($ftxts,'■',$px1+$fclen);
            if($px2 === false) $px2 = strlen($ftxts)-1;
            $gwlb = preg_replace('/^[\s　√☆★●◆■▲△◎□☑☒✔]+|[\s　√☆★●◆■▲△◎□☑☒✔]+$/us','',substr($ftxts,$px1 + $fclen,$px2-$px1-$fclen));
            $px1 = strpos($gwlb,' ');
            if($px1 === FALSE) $px1 = PHP_INT_MAX;
            $px2 = strpos($gwlb,'　');
            if($px2 === FALSE) $px2 = PHP_INT_MAX;
            $px1 = min($px1,$px2);
            if($px1 > 3) $gwlb = substr($gwlb,0,$px1);
        }
    }
    return $gwlb;
}


/**
 * @param array $rows 数据行
 * @param array|null $questions 问题集
 * @param float $tolerance_rate 容错比率
 * @return array|bool
 */
function OrderQWItems_xjdl(array &$rows,array &$questions=null,$tolerance_rate=0.6){
    static $questions_xjdl = array('热身话题：疫情期间各方面近况如何？作为青年，对于当前中美关系有什么感受或态度？',
        '1.你觉得当下国家的发展形势如何？单位的发展前景如何？',
        '2.你认为什么是当下青年最应该有的特质？你觉得当前“青年的担当”具体包括什么？',
        '3.你对思想教育活动的态度如何？什么样的思想教育方式是你最愿意参与的？',
        '4.觉得目前的工作压力如何？',
        '5.什么最能让你对工作充满热情？什么是你觉得最不满意的地方？',
        '6.你期望中的理想型上级是一种怎样的上级？',
        '7.对于国网公司战略目标和新疆公司战略实施行动方向，你有多大程度的了解？',
        '8.你对自己未来的职业发展有什么期望？',
        '9.对于提升工作本领，你觉得最有效的方式是什么？',
        '10.你最热衷于参加哪类培训？',
        '11.你觉得当前最主要的压力是什么？打算如何缓解？',
        '12.你有哪些兴趣爱好？希望单位为此提供什么？',
        '13.你最希望工会帮你解决哪些实际困难，或在哪些方面发挥更大作用？',
        '14.还有哪些其他意见建议？');
    $orderet = array();
    if (!empty($rows)) {
        if ($questions == null) $questions = $questions_xjdl;
        $rlen = count($rows);
        $qlen = count($questions);
        if ($rlen >= $qlen) {
            $j = 0;
            $wv = null;
            $lastMatch = -1;
            $cur_qi = 0;//当前问题
            $similar_list = array();
            for ($r = 0; $r < $rlen; $r++){
                for ($q = 0; $q < $qlen; $q++){
                    similar_text($questions[$q],$rows[$r],$percent);
                    if($percent > 80){
                        $similar_list[$r] = $q;
                        continue 2;
                    }
                }
                $similar_list[$r] = -1;
            }

            $match_time = 0;
            for ($g = 0; $g < $qlen; $g++){
                $id = array_search($g,$similar_list,true);
                if($id === FALSE){
                    $orderet[$questions[$g]] = '';
                }
                else{
                    $anwT = '';
                    $match_time++;
                    for($k = $id+1;$k<$rlen;$k++){
                        if($similar_list[$k] == -1){
                           if($anwT != '') $anwT .= ANSWER_NEWLINE . $rows[$k];
                           else $anwT = $rows[$k];
                        }
                        else break;
                    }
                    $orderet[$questions[$g]] = $anwT;
                }
            }
            if ((float)$match_time / count($questions) < $tolerance_rate) $orderet = array();
        }
    }
    if(empty($orderet)) return false;
    return $orderet;
}

/**
 * 枚举指定目录
 * @param string $dirname 目录路径
 * @param mixed &$dirs 输出的结果数组,结果将存储在$dirs['dir'],$dirs['file']内
 * @param int $type 操作类型,位0表示文件,位1表示目录,位2保留,位3为是否禁止递归;默认为1,递归取文件
 * @param string|null $path_match 路径匹配式,必须是完整正则式
 * @return int 共获取多少个文件或者目录
 */
function listDir(string $dirname, &$dirs,int $type = 1, $path_match = null): int
{
    $ret = 0;
    if (!@is_dir($dirname)) {
        return $ret;
    }
    if( ! in_array($dirname[strlen($dirname) - 1],['\\','/'])){
        $dirname .= DIRECTORY_SEPARATOR;
    }
    if( ! is_array($dirs)) $dirs = [];
    $dir = opendir($dirname);
    while (($file = readdir($dir)) !== false) {//组装文件夹和文件的路径
        $filename = $dirname . $file;
        if ($file != '.' && $file !== '..') {
            if (is_dir($filename)) {
                if (($type & 2) > 0) {
                    if (!isset($dirs['dir'])) $dirs['dir'] = [];
                    if(empty($path_match) || @preg_match($path_match,$filename) > 0){
                        $dirs['dir'][] = $filename;
                        $ret++;
                    }
                }
                $recursion = (($type & 8) == 0);//是否递归,默认为是
                if($recursion){
                    $ret += listDir($filename,$dirs, $type,$path_match);
                }
            } else {
                if (($type & 1) > 0) {
                    if (!isset($dirs['file'])) $dirs['file'] = [];
                    if(empty($path_match) || @preg_match($path_match,$filename) > 0){
                        $dirs['file'][] = $filename;
                        $ret++;
                    }
                }
            }
        }
    }
    return $ret;
}

function chg_charset(string $data, string $to_encoding = 'UTF-8')
{
    $from_encoding = mb_detect_encoding($data, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5','GB18030'));
    if($from_encoding != $to_encoding){//需要转换
        $data2 = iconv($from_encoding, $to_encoding, $data);
        if ($data2 === false) {
            $data2 = iconv('UTF-8//TRANSLIT', $to_encoding, $data);
            if ($data2 === false) {
                $data2 = iconv('UTF-8//IGNORE', $to_encoding, $data);
            }
        }
        $data = $data2;
    }
    return $data;
}

